import React from 'react'
import { NavLink } from 'react-router-dom'
import { connect } from 'react-redux'
import './groupStyle.less'
import JoinRuleDialog from './JoinRuleDialog'
import CreateGroupDialog from './CreateGroup'
import GroupModalDialog from './ConfirmDialog'

const mapStateToProps = (state) => {
  return {
    userInfo: state.app.userInfo,
    agentLevel: state.app.agentLevel,
    shareCrowdIdValid: state.dynamics.shareCrowdIdValid
  }
}
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    changeCurrentGroup: (groupData) => dispatch(global.allActions.groupActions.changeCurrentGroup(groupData)),
    shareCrowdIdInvalid: () => dispatch(global.allActions.appActions.shareCrowdIdInvalid())
  }
}
class Group extends React.Component<any, any> {
  public constructor(props) {
    super(props)
    this.state = {
      rulesList: [],
      showJoinRule: false,
      showCreate: false,
      myJoinedGroups: [],
      hasCreatedGroup: false,
      showModalDialog: false,
      dialogText: ''
    }
  }

  public componentDidMount() {
    this.queryGroupInfo()
  }

  queryGroupInfo() {
    const url = `${config.pre}/crowd/info/${Cookies.get('areaCode')}/newcrowd`
    fetchJson(url).then(data => {
      console.log(data);
      if (data.result) {
        this.setState({ myJoinedGroups: [] })
        if (data.result == 600) {
          sessionStorage.setItem('result600', 'true')
          window.location.href = data.data //
        }
      } else {
        const hasCreatedGroup = data.data.dataList.some(group => group.owner === 1)
        this.setState({ myJoinedGroups: data.data.dataList, hasCreatedGroup })

        const _url = `${config.pre}/crowd/room/crowdInfo/${Cookies.get('areaCode')}`
        const opt = { type: 'GET' }
        let applyCrowdId = +queryString.parse(window.location.href).crowdId
        let errorCode = queryString.parse(window.location.href).errorCode
        errorCode = errorCode ? +errorCode.match('404') : null
        if(this.props.shareCrowdIdValid) {
          this.state.myJoinedGroups.forEach(group => {
            if (group.id == applyCrowdId) {
              this.groupClicked(group)
            }
            if(errorCode == 404) {
              this.setState({dialogText: '已申请加入该俱乐部', showModalDialog: true})
              this.props.shareCrowdIdInvalid()
            }
          })
        }
        if (sessionStorage.getItem('result600')) {
          fetchJson(_url, opt).then(_data => {
            console.error('get group id', _data)
            // {result:0, message: '', data: {}}
            // alert(_data.data.id)
            sessionStorage.removeItem('result600')
            this.state.myJoinedGroups.forEach(group => {
              if (group.id === _data.data.id) {
                this.groupClicked(group)
              }
            })

          })
        }
      }
    })
  }

  handleCreate() {
    this.setState({ showCreate: true })
  }

  groupClicked(groupData) {
    window.location.hash = 'Inner'
    // this.props.changeCurrentGroup(groupData)
  }

  public render() {
    const { userInfo } = this.props
    const { inviteId, tip, rulesList, showJoinRule, showCreate, myJoinedGroups, hasCreatedGroup, showModalDialog, dialogText } = this.state
    console.log('myJoinedGroups', myJoinedGroups);
    return <div className="view-page group-view">
      <img src="img/group/group-di.png?v=20181201" className="full pos-abs" alt="" />
      <div className="underbg">
        <div className="group-top text-center">
          {/* <img src="img/group/group-join-btn.png?v=20181201" onClick={() => this.setState({ showJoinRule: true })} className="join-group-btn" alt="" /> */}
        </div>
        <div className="group-middle">
          {/* <img src="img/group/content-di.png?v=20181201" className="pos-abs full" alt="" /> */}
          <div className="middle-stone-upper pure-g transparent-bg">
            <div className="pure-u-1-2 vh-center">
              <img src="img/groupNew/join-group-new.png?v=20181201" onClick={() => this.setState({ showJoinRule: true })} className="group-top-btn" alt="" />
            </div>
            <div className="pure-u-1-2 vh-center">
              <img src="img/groupNew/createGroup-btn.png?v=20181201" onClick={this.handleCreate.bind(this)} className="group-top-btn" alt="" />
            </div>
          </div>
          <ul className="middle-stone scroll-h">
            已加入{myJoinedGroups.length}个俱乐部
            {
              myJoinedGroups.map(groupData => {
                const games = _.take(groupData.playList, 2).map((play, pIndex) => (<span key={pIndex}>{play + ' '}</span>))
                return <div key={groupData.crowdId} className="group-item pure-g transparent-bg" onClick={this.groupClicked.bind(this, groupData)}>
                  <div className="pure-u-5-24 vh-center">
                    <img className="group-new-header" src={groupData.crowdHead} alt="群头像" />
                  </div>
                  <div className="pure-u-14-24">
                    <p className="group-name orange">{groupData.crwodName}</p>
                    <p className="group-number">俱乐部ID: {groupData.crowdId}</p>
                    <p className="group-game">游戏: {games}{groupData.playList.length > 2 ? '...' : ''}</p>
                  </div>
                  <div className="pure-u-5-24 v-center">
                    成员{groupData.number}人
                  </div>
                </div>
              })
            }
          </ul>
        </div>
        <div className="inner-bottom">
            <div className="text vh-center"><span>我加入的俱乐部</span></div>
            <NavLink to="/UserCenter"><img className="back" src="img/app/back.png?v=20181201" alt="" /></NavLink>
        </div>
      </div>
      {
        showJoinRule ? <JoinRuleDialog close={() => this.setState({ showJoinRule: false })}></JoinRuleDialog> : null
      }
      {
        showCreate ? <CreateGroupDialog queryGroupInfo={this.queryGroupInfo.bind(this)} hasCreatedGroup={hasCreatedGroup} close={() => this.setState({ showCreate: false })}></CreateGroupDialog> : null
      }
      {
        showModalDialog ? <GroupModalDialog confirm={() => {this.setState({showModalDialog: false})}} isModal={false} modalContent={dialogText}></GroupModalDialog> : null
      }
    </div>
  }

}

export default connect(mapStateToProps, mapDispatchToProps)(Group)